﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

using Opentao.NotificationService.Common.Data.Constants;
using Opentao.NotificationService.Common.Data.DTO;
using Opentao.NotificationService.Services.EmailService;

namespace Opentao.NotificationService.Business.Objects
{
    /// <summary>
    /// Бизнес-объект для работы с рассылаемыми сообщениями.
    /// </summary>
    public static class MessageBO
    {
        /// <summary>
        /// Разослать сообщения.
        /// </summary>
        /// <param name="messages"> Сообщения, подлежащие рассылке. </param>
        public static void SendMessages( List<Message> messages )
        {
            using( var eventTypeBO = new EventTypeBO() )
            using( var importanceLevelBO = new ImportanceLevelBO() )
            using( var mailer = new Mailer() ) {
                foreach( var message in messages ) {
                    List<string> addresses;
                    string subject;
                    string text;

                    var defaultEventTitle = ConfigurationManager.AppSettings[ StringConstants.defaultEventTitle ];

                    if( eventTypeBO.CheckForExistence( message.EventType ) ) {
                        addresses = eventTypeBO.GetSubscribers( message.EventType ).Select( s => s.Email ).ToList();
                        subject = string.Format( "{0} - {1}", message.ImportanceLevel, message.EventType );
                        text = message.Text;
                    }
                    else {
                        addresses = eventTypeBO.GetSubscribers( defaultEventTitle ).Select( s => s.Email ).ToList();
                        subject = string.Format( "{0} - {1}", message.ImportanceLevel, defaultEventTitle );
                        text = string.Concat( message.EventType, Environment.NewLine, message.Text );
                    }

                    if( importanceLevelBO.CheckUseEmail( message.ImportanceLevel ) )
                        mailer.DistributeMessage( addresses, subject, text );

                    // TODO: Реализовать имитацию рассылки SMS.
                }
            }
        }
    }
}